package com.project.control.system.user;

import cn.hutool.core.date.DateUtil;
import com.project.bean.system.TblRoleBean;
import com.project.bean.system.TblUserBean;
import com.project.control.BaseController;
import com.project.entity.system.user.UserInfoEntity;
import com.project.service.system.UserService;
import com.project.utils.ShiroUtils;
import com.project.utils.annotation.AutoValid;
import com.project.utils.file.FileUtil;
import com.project.utils.layui.PageUtils;
import com.project.utils.result.ResultModel;
import com.project.utils.result.ResultTools;
import com.project.utils.token.*;
import com.project.utils.uuid.UUIDEnum;
import com.project.utils.uuid.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;


/**
 * @author : Mr.Yan
 * @program : com.project.control.login
 * @create : 2020/03/28
 * @description : 登陆拦截器
 */
@Slf4j
@RestController
@RequestMapping(value = "/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    /**
     * @author : Mr.Yan
     * @create : 2020/3/29
     * @description : 登陆接口返回 token
     */
    @PostMapping(value = "/login")
    @LoginToken
    public ResultModel login(@RequestBody TblUserBean tblUserBean) {
        log.info("登陆 [user/login] 接口");
        try {
            /** 登陆token 创建，为后期单点登陆进行加入，创建token值*/
            String token = JwtUtil.createJWT(tblUserBean.getUserName(), tblUserBean.getPassWord());
            JwtToken jwtToken = new JwtToken(token);
            Subject subject = SecurityUtils.getSubject();
            subject.login(jwtToken);
            UserInfoEntity userInfoEntity = ShiroUtils.getPrincipal();
            Set<String> roles = new LinkedHashSet<>();
            Set<TblRoleBean> tblRoleBeanSet = userInfoEntity.getRoles();
            for (TblRoleBean tblRoleBean : tblRoleBeanSet) {
                roles.add(tblRoleBean.getPermission());
            }
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("token", token);
            resultMap.put("roles", roles);
            log.info("结束");
            return ResultTools.success(resultMap);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            log.error(String.format("结束：%s",e.getMessage()));
            return ResultTools.fail(e.getMessage());
        }
    }

    /**
      * @author : Mr.Yan
      * @create : 2020/6/22
      * @description : 获取当前登陆得用户得信息
      */
    @GetMapping(value = "/info")
    @CheckToken
    public ResultModel info() {
        log.info("登陆 [user/info] 接口");
        try {
            UserInfoEntity userInfoEntity = ShiroUtils.getPrincipal();
            Set<String> roles = new LinkedHashSet<>();
            Set<TblRoleBean> tblRoleBeanSet = userInfoEntity.getRoles();
            for (TblRoleBean tblRoleBean : tblRoleBeanSet) {
                roles.add(tblRoleBean.getPermission());
            }
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("user", userInfoEntity);
            resultMap.put("roles", roles);
            log.info("结束");
            return ResultTools.success(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(String.format("结束：%s",e.getMessage()));
            return ResultTools.fail(e.getMessage());
        }
    }

    @GetMapping(value = "/list")
    @CheckToken
    public ResultModel list(@Valid PageUtils pageUtils, BindingResult result){
        log.info("分页 [user/list] 接口");
        PageQuery<TblUserBean> page = userService.find_Page(pageUtils);
        return ResultTools.success(page);
    }

    @GetMapping(value = "/list/download")
    @CheckToken
    public void download(PageUtils pageUtils){
        try {
            log.info("导出 [user/list/download] 接口");
            PageQuery<TblUserBean> page = userService.find_Page(pageUtils);
            List<Map<String, Object>> list = new ArrayList<>();
            for (TblUserBean userDTO : page.getList()) {
                Map<String,Object> map = new LinkedHashMap<>();
                map.put("用户名", userDTO.getUserName());
                map.put("状态", userDTO.getIsValid().equals("Y") ? "启用" : "禁用");
                map.put("创建日期", userDTO.getSysCreateTime());
                list.add(map);
            }
            FileUtil.downloadExcel(list, super.getResponse());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(String.format("结束：%s",e.getMessage()));
        }
    }

    /**
      * @author : Mr.Yan
      * @create : 2020/6/3
      * @description : 添加用户接口
      */
    @PostMapping(value = "/add")
    @CheckToken
    @AutoValid
    public ResultModel add(@Valid @RequestBody  TblUserBean tblUserBean, BindingResult result){
        log.info("添加 [user/add] 接口");
        try {
            tblUserBean.setUserId(UUIDUtils.getUUID(UUIDEnum.USER));
            tblUserBean.setSysCreateTime(DateUtil.parse(DateUtil.now())); // 创建时间
            tblUserBean.setSysCreateUserId(ShiroUtils.getPrincipal().getUserId()); // 创建人Id
            int primaryKey = userService.insert_Selective(tblUserBean);
            if (primaryKey<=0) {
                return ResultTools.fail();
            }
            return ResultTools.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(String.format("结束：%s",e.getMessage()));
            return ResultTools.fail(e.getMessage());
        }
    }

    /**
     * @author : Mr.Yan
     * @create : 2020/6/3
     * @description : 更新用户接口
     */
    @PutMapping(value = "/update")
    @CheckToken
    public ResultModel update(@RequestBody TblUserBean tblUserBean){
        log.info("添加 [user/update] 接口");
        try {
            tblUserBean.setSysUpdateTime(DateUtil.parse(DateUtil.now())); // 更新时间
            tblUserBean.setSysUpdateUserId(ShiroUtils.getPrincipal().getUserId()); // 更新人Id
            int primaryKey = userService.update_Selective_ByPK(tblUserBean);
            if (primaryKey<=0) {
                return ResultTools.fail();
            }
            return ResultTools.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(String.format("结束：%s",e.getMessage()));
            return ResultTools.fail(e.getMessage());
        }
    }

    /**
     * @author : Mr.Yan
     * @create : 2020/6/3
     * @description : 删除用户接口
     */
    @DeleteMapping(value = "/delete")
    @CheckToken
    public ResultModel delete(@RequestBody List<Integer> pkList){
        log.info("添加 [user/update] 接口");
        try {
            List<TblUserBean> userBeanList = new ArrayList<>();
            for (Integer pk: pkList) {
                TblUserBean userBean = new TblUserBean();
                userBean.setId(pk);
                userBean.setSysUpdateTime(DateUtil.parse(DateUtil.now())); // 更新时间
                userBean.setSysUpdateUserId(ShiroUtils.getPrincipal().getUserId()); // 更新人Id
                userBean.setIsDelete(String.valueOf("Y"));
                userBeanList.add(userBean);
            }
            int primaryKey = userService.update_BatchSelective_ByPK(userBeanList);
            if (primaryKey<=0) {
                return ResultTools.fail();
            }
            return ResultTools.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(String.format("结束：%s",e.getMessage()));
            return ResultTools.fail(e.getMessage());
        }
    }
}
